import {Type} from '@angular/core';

export class ComItem {
    constructor(public component: Type<any>, public tagData: any) {
        if (this.tagData.frontData && Object.keys(this.tagData.frontData).length > 0  && this.tagData.data) {

            const originalStr = JSON.stringify(this.tagData.data);
            const variables = this.tagData.frontData;
            const resultStr = this.replaceFrontCalculateCalls(originalStr, variables);
            this.tagData.data = JSON.parse(resultStr);
        }
    }


    fun(a) {
        return a + 1;
    }
    evaluateExpression(expression: string, variables: { [key: string]: any } = {}): any {
        const that = this;
        try {
            // 使用Function构造函数和提供的变量对象来创建一个新函数
            const func = new Function('variables', `with(variables) { return ${expression}; }`);
            // 调用该函数并传入变量对象
            return func(variables);
        } catch (error) {
            // 捕获并处理错误
            console.error('Error evaluating expression:', expression, error);
            // 可以选择返回某个默认值或抛出错误
            return ""; // 或 throw error;
        }

    }

     replaceFrontCalculateCalls(str, variables) {
        // 正则表达式匹配 frontCalculate(...)
        const regex = /frontCalculate\{\{([^}}]*)\}\}/g;
        return str.replace(regex, (match, capture) => {
            console.log('capture0:' + capture);
            // 去除括号内的空格并替换变量
            let expr = capture.replace(/\s/g, '');
            console.log('capture1:' + expr);
            // 给自定义方法加上this.方便调用
            expr = expr.replace(/fontFun/g, 'window.appGlobalService.fontFun');
            console.log('capture2:' + expr);
            // 计算或评估表达式
            return this.evaluateExpression(expr, variables);
        });
    }



}
